package com.example.dangerouscargodriver.controller;

import android.content.Context;
import android.content.SharedPreferences;
import android.os.Message;
import android.util.Log;

import com.baiju.netmanager.Http.HttpRequest;
import com.baiju.netmanager.Http.IHttpRequest;
import com.baiju.netmanager.Http.INetResponse;
import com.example.dangerouscargodriver.DangerousCargoDriverApplication;
import com.example.dangerouscargodriver.event.Event;
import com.example.dangerouscargodriver.event.LoadHttpResourceStatus;
import com.example.dangerouscargodriver.module.ResponseInfo;
import com.example.dangerouscargodriver.entry.UserInfo;
import com.example.dangerouscargodriver.param.RemoteAPI;
import com.example.dangerouscargodriver.param.RemoteAPICmd;
import com.google.gson.Gson;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.HashMap;

public class UserInfoController extends Controller{

    private static final String TAG = "UserInfoController";
    private static final  int MSG_ADD_LISTENER = 0;
    private static final  int MSG_LOAD_HTTP_USER_DONE = 1;
    private static final  int MSG_LOAD_HTTP_USER = 2;

    public static final int EVENT_USER_LOADING = 0;
    public static final int EVENT_USER_LOAD_DONE = 1;

    private static UserInfoController mInstance = null;
    private HttpResponseListener mHttpListener = null;

    private HashMap<java.lang.Class, IControllerEventListener> mControllerListener = null;

    private UserInfo mUserInfo = null;

    private HttpRequest mHttp = null;

    private Context mContext = null;

    private int mLoadUserInfoStatus = EVENT_USER_LOADING;

    public static UserInfoController Instance(){
        if(mInstance == null){
            mInstance = new UserInfoController(DangerousCargoDriverApplication.getAppContext());
        }

        return mInstance;
    }

    private UserInfoController(Context context){
        mContext = context;
        mHttpListener = new HttpResponseListener();
        mHttp = HttpRequest.Instance(context);
        mHttp.attachResponseListener(mHttpListener, UserInfoController.class);
        mHttp.startUp();

        mControllerListener = new HashMap<>();

        if(getUserInfo() == null) {
            getHttpUserInfo();
        }
        else{
            mLoadUserInfoStatus = EVENT_USER_LOAD_DONE;
            Message msg = new Message();
            msg.what = MSG_LOAD_HTTP_USER_DONE;
            sendMessage(msg);
        }
    }

    public boolean attachControllerListener(java.lang.Class object, IControllerEventListener listener){
        if(mControllerListener.containsKey(object)){
            return false;
        }
        else {
            mControllerListener.put(object, listener);
            return true;
        }
    }

    public boolean unAttachControllerListener(java.lang.Class object, IControllerEventListener listener){
        if(mControllerListener.containsKey(object) && mControllerListener.get(object) == listener){
            mControllerListener.remove(object);
            return true;
        }
        else {
            return false;
        }
    }

    public UserInfo getUserInfo() {
        if(mUserInfo == null) {
            SharedPreferences sharedPreferences =
                    DangerousCargoDriverApplication.getAppContext().getSharedPreferences(
                            "wsj_login",
                            Context.MODE_PRIVATE);
            String user = sharedPreferences.getString("user_info", null);
            if(user != null) {
                Gson gson = new Gson();
                mUserInfo = gson.fromJson(user, UserInfo.class);
                Log.d(TAG, "mUserInfo: " + mUserInfo.toString());
            }
        }

        return mUserInfo;
    }

    public void updateUserInfo(){
        getHttpUserInfo();
    }

    public void clearUserInfo(){
        SharedPreferences sharedPreferences =
                DangerousCargoDriverApplication.getAppContext().getSharedPreferences("wsj_login",
                        Context.MODE_PRIVATE);
        SharedPreferences.Editor editor = sharedPreferences.edit();
        editor.putString("user_info", null);
        editor.commit();
        mUserInfo = null;
    }

    @Override
    protected void handleControllerMessage(Message msg){
        switch (msg.what){
            case MSG_ADD_LISTENER:
                LoadHttpResourceStatus status = new LoadHttpResourceStatus();
                status.setWhat(mLoadUserInfoStatus);
                mControllerListener.get(msg.obj).onEvent(Event.EVENT_LOAD_HTTP_USER_INFO, status.toJson());
                break;
            case MSG_LOAD_HTTP_USER_DONE:
                for (Class key : mControllerListener.keySet()) {
                    LoadHttpResourceStatus httpResourceStatus = new LoadHttpResourceStatus();
                    httpResourceStatus.setWhat(mLoadUserInfoStatus);
                    mControllerListener.get(key).onEvent(Event.EVENT_LOAD_HTTP_USER_INFO, httpResourceStatus.toJson());
                }
                break;
            case MSG_LOAD_HTTP_USER:
                getHttpUserInfo();
                break;
            default:
                break;
        }
    }

    private void getHttpUserInfo(){
        SharedPreferences sharedPreferences =
                DangerousCargoDriverApplication.getAppContext().getSharedPreferences(
                "wsj_auth",
                Context.MODE_PRIVATE);
        String token = sharedPreferences.getString("token", null);
        HashMap<String, String> header = new HashMap<String, String>();
        header.put("token", token);
        header.put("app-type", "Android");

        mHttp.sendRequest(
                IHttpRequest.RequestMethod.GET_METHOD,
                RemoteAPI.REQUEST_GET_USER_INFO,
                header,
                null,
                RemoteAPICmd.REQUEST_GET_USER_INFO,
                UserInfoController.class);
    }

    private void setCurrentUserInfo(String user){
        Gson gson = new Gson();
        UserInfo userInfo = gson.fromJson(user, UserInfo.class);
        if(userInfo != null) {
            SharedPreferences sharedPreferences =
                    DangerousCargoDriverApplication.getAppContext().getSharedPreferences("wsj_login",
                            Context.MODE_PRIVATE);
            SharedPreferences.Editor editor = sharedPreferences.edit();
            editor.putString("user_info", user);
            editor.commit();

            mUserInfo = userInfo;
            mLoadUserInfoStatus = EVENT_USER_LOAD_DONE;
        }
    }

    private void setIconPath(String path){
        SharedPreferences sharedPreferences =
                DangerousCargoDriverApplication.getAppContext().getSharedPreferences("wsj_login",
                        Context.MODE_PRIVATE);
        SharedPreferences.Editor editor = sharedPreferences.edit();
        editor.putString("icon", path);
        editor.commit();
    }

    private class HttpResponseListener implements INetResponse {

        @Override
        public void onResponse(int actionId, String response) {
            try {
                JSONObject res = new JSONObject(response);
                Gson gson = new Gson();
                if(actionId == RemoteAPICmd.REQUEST_GET_USER_INFO){
                    Log.d(TAG, "onResponse: " + response);
                    ResponseInfo responseInfo = gson.fromJson(response, ResponseInfo.class);
                    if(responseInfo != null && responseInfo.getStatus() == 1){
                        JSONObject data = res.getJSONObject("data");
                        setCurrentUserInfo(data.toString());

                        Message msg = new Message();
                        msg.what = MSG_LOAD_HTTP_USER_DONE;
                        sendMessage(msg);
                    }
                    else{

                    }
                }
                else{

                }
            }
            catch (JSONException e) {
                e.printStackTrace();
            }
        }

        @Override
        public void onErrorResponse(int actionId, String response) {
            if(actionId == RemoteAPICmd.REQUEST_GET_USER_INFO){
                Message message = new Message();
                message.what = MSG_LOAD_HTTP_USER;
                sendMessageDelayed(message, 1000);
            }
        }
    }
}
